package com.xspace.android.imcommon.service;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import com.xspace.android.imcommon.fileupload.IUploadCallback;
import com.xspace.android.imcommon.fileupload.UploadManager;
import com.xspace.android.imcommon.interfaces.ChatAidl;
import com.xspace.android.imcommon.interfaces.ChatCallback;
import com.xspace.android.imcommon.interfaces.ChatListAidl;
import com.xspace.android.imcommon.interfaces.ChatSnapCallback;
import com.xspace.android.imcommon.interfaces.FriendAidl;
import com.xspace.android.imcommon.interfaces.FriendCallback;
import com.xspace.android.imcommon.interfaces.IMessage;
import com.xspace.android.imcommon.interfaces.IMessage.Stub;
import com.xspace.android.imcommon.interfaces.IMsgCallback;
import com.xspace.android.imcommon.interfaces.LoginCallBack;
import com.xspace.android.imcommon.interfaces.MucChatAidl;
import com.xspace.android.imcommon.interfaces.PushAidl;
import com.xspace.android.imcommon.interfaces.PushCallback;
import com.xspace.android.imcommon.interfaces.PushListAidl;
import com.xspace.android.imcommon.interfaces.SMSCallback;
import com.xspace.android.imcommon.interfaces.SmsListAidl;
import com.xspace.android.imcommon.message.FriendManager;
import com.xspace.android.imcommon.message.SmsManager;
import com.xspace.android.imcommon.utils.ImPreferences;
import com.xspace.android.imcommon.utils.WakeLockManager;
import com.xspace.android.imcommon.utils.sk.ChatMessage;
import com.xspace.android.xafcommon.util.AppUtils;
import com.xspace.android.xafcommon.util.LogUtils;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class ClientService extends Service {
	private static final int REFURSHCONTACTDELAYMILLIS = 15000;
	private Timer mHeartTimer;
	private boolean mIsHandler = false;
//	private XMPPConnectionMg mXMPPConnectionMg;
//	private ClientChatManager mClientChatManager;
//	private PushManager mPushManager;
	private FriendManager mFriendManager;
//	private ServiceStateThread mServiceStateThread;
	private SmsManager mSmsManager;
	private  PendingIntent pendingIntent  ;
//	private XMucChatManager xMucChatManager;
    private UploadManager mUploadManager;
	/**
	 * Constructor.
	 */
	public ClientService() {
//		Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
//
//			@Override
//			public void uncaughtException(Thread thread, Throwable ex) {
//				if (ex != null)
//					LogUtils.e(ex.getLocalizedMessage());
//				else
//					ex.printStackTrace();
//			}
//		});
	}

	private boolean istop = false;

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onCreate() {
		super.onCreate();
		Log.v("clientservice","*************onCreate*************");
//		mClientChatManager = new ClientChatManager(this);
//		mXMPPConnectionMg = new XMPPConnectionMg(this, mClientChatManager);
//		mPushManager = new PushManager(this, mClientChatManager);
		mFriendManager = new FriendManager(this);
		mSmsManager = new SmsManager(this);
//		mServiceStateThread = new ServiceStateThread(this, mXMPPConnectionMg);
//		xMucChatManager=new XMucChatManager(this, mXMPPConnectionMg.getConnected());
//		mXMPPConnectionMg.setxMucChatManager(xMucChatManager);
		//mServiceStateThread.startRequest();
		LogUtils.i("*************onCreate111111111111111111*************");
//		setAlarmCheckService(this, 60*1000);
		mUploadManager=new UploadManager(this);
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		Log.i("clientservice","ClientService*************onStart*************");
//		if(mXMPPConnectionMg!=null&&mXMPPConnectionMg.isConnected()){
//			LogUtils.v("ClientService*************hasconnected*************");
//			return;
//		}
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				connectRunnable();
			}
		});
		t.start();
	}

	private synchronized void connectRunnable() {
//		if (mXMPPConnectionMg != null && AppUtils.isConnected(this)) {
//			LogUtils.i("*************connect*************");
//			mXMPPConnectionMg.connectServer();
//		} else {
//			LogUtils.i("*************no network*************");
//		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onDestroy() {
		Log.i("clientservice","*************onDestroy*************");
		super.onDestroy();
//		if (mXMPPConnectionMg != null && mXMPPConnectionMg.isConnected()) {
//			LogUtils.i("*************disconnect*************");
//			mXMPPConnectionMg.disconnect();
//		}
		cancelAlarm(this);
		WakeLockManager.releaseWakeLock();
		istop = true;
//		mXMPPConnectionMg = null;
	}
    
	@Override
	public boolean onUnbind(Intent intent) {
    	Log.i("clientservice", "unbindService>>>>>");
//    	if (mXMPPConnectionMg != null && mXMPPConnectionMg.isConnected()) {
//    		Log.i("clientservice","*************disconnect*************");
//			mXMPPConnectionMg.disconnect();
//		}
		cancelAlarm(this);
		WakeLockManager.releaseWakeLock();
		istop = true;
		return super.onUnbind(intent);
	}

//	// 发送心跳
//	private void startSendHeart() {
//		// 心跳
//		if (mHeartTimer != null) {
//			mHeartTimer.cancel();
//		}
//		mHeartTimer = new Timer();
//		mHeartTimer.schedule(new TimerTask() {
//			@Override
//			public void run() {
//				if (mXMPPConnectionMg != null && mXMPPConnectionMg.isConnected()) {
//					LogUtils.i("*************send heat*************");
//					mXMPPConnectionMg.sendPingPacket();
//				} else {
//					LogUtils.i("*************send heat cancel*************");
//					mHeartTimer.cancel();
//				}
//			}
//		}, 1000*120, 180*1000);
//	}

	private String nmgGetShortSMS(String sms) {
		String[] smsArr = sms.split("@");
		String shortSMS = "";
		if (smsArr.length > 1) {
			shortSMS = smsArr[1];
		}

		return shortSMS;
	}

	private String qacGetShotSMS(String sms) {
		String[] smsArr = sms.split("，");
		String shortSMS = "";
		if (smsArr.length > 0) {
			shortSMS = smsArr[0];
		}

		return shortSMS;
	}

	private String nmgGetShortSMS2(String sms) {
		String[] smsArr = sms.split("!");
		String shortSMS = "";
		if (smsArr.length > 0) {
			shortSMS = smsArr[0];
		}

		return shortSMS;
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return mBinder;
	}

	IMessage.Stub mBinder = new Stub() {

		@Override
		public void login(int iocId, String userName, String password, String host,
				int port, String url, LoginCallBack mLoginCallBack) throws RemoteException {
			System.out.println("*************send heat login()*************");
//			ImConstants.URL_SUFFIX = url;
//			mXMPPConnectionMg.login(userName, password, mLoginCallBack, host, port);
			ImPreferences.getInstance(ClientService.this).setPfString(AppUtils.host, host);
			ImPreferences.getInstance(ClientService.this).setPfInt(AppUtils.port, port);
			ImPreferences.getInstance(ClientService.this).setPfString(AppUtils.url, url);
			ImPreferences.getInstance(ClientService.this).setPfString(AppUtils.userName, userName);
			ImPreferences.getInstance(ClientService.this).setPfString(AppUtils.password, password);
			ImPreferences.getInstance(ClientService.this).setPfInt(AppUtils.IM_IOC, iocId);
			String jid = ImPreferences.getInstance(ClientService.this).getPfString(AppUtils.userName);
			Log.i("broad"," login clientservice jid"+jid+"url:"+url+" host:"+host+" port:"+port);
		}

		@Override
		public void logOut() throws RemoteException {
			// TODO Auto-generated method stub
			LogUtils.i("*************send heat logOut()*************");
//			mXMPPConnectionMg.logOut();
			ImPreferences.getInstance(ClientService.this).setPfString(AppUtils.host, "");
			ImPreferences.getInstance(ClientService.this).setPfInt(AppUtils.port, 0);
			ImPreferences.getInstance(ClientService.this).setPfString(AppUtils.url, "");
			ImPreferences.getInstance(ClientService.this).setPfString(AppUtils.userName, "");
			ImPreferences.getInstance(ClientService.this).setPfString(AppUtils.password, "");
			// try {
			// mServiceStateThread.stopRequest();
			// } catch (Exception e) {
			// e.printStackTrace();
			// }
			// stopSelf();
			// onDestroy();
			// android.os.Process.killProcess(android.os.Process.myPid());
			// killService();
		}

		@Override
		public void initPush(PushCallback mPushCallback) throws RemoteException {
			// TODO Auto-generated method stub
			System.out.println("-------------11---mPushCallback:" + mPushCallback);
//			mClientChatManager.initPush(mPushCallback);
		}

		@Override
		public void saveOrUpdatePush(String owner, PushAidl pushMsg) throws RemoteException {
			// TODO Auto-generated method stub
//			mPushManager.saveOrUpdatePush(owner, pushMsg);
		}

		@Override
		public PushListAidl queryPushList(String owner, String channelName) throws RemoteException {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public PushListAidl queryPushChildList(String mPushUserID, String mPlatformID, String owner, String sendtimeStart, String sendtimeEnd,String key) throws RemoteException {
			// TODO Auto-generated method stub
			return null;
		}
		
		@Override
		public PushListAidl queryPushChildAllList(String owner,String channelName) throws RemoteException {
			// TODO Auto-generated method stub
			return null;
		}


		@Override
		public List<String> getMsgBodyTypeArr() throws RemoteException {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public void deleteSinglePushMsg(int msgId) throws RemoteException {
			// TODO Auto-generated method stub
//			mPushManager.deleteSinglePushMsg(msgId);
		}

		@Override
		public void deletePushMsg(String mPlatformId, String pushUserID, String barejid) throws RemoteException {
			// TODO Auto-generated method stub
//			mPushManager.deletePushMsg(mPlatformId, pushUserID, barejid);
		}

		@Override
		public void queryChatMsgSnaps() throws RemoteException {
			// TODO Auto-generated method stub

		}

		@Override
		public boolean deleteImUser(String userId) throws RemoteException {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public boolean deleteMsg(int msgId) throws RemoteException {
			// TODO Auto-generated method stub
			return false;
		}
		@Override
		public void initSendMessage(IMsgCallback callback, String userName, String toUserName) throws RemoteException {
			// TODO Auto-generated method stub
//			mClientChatManager.initSendMessage(callback, userName, toUserName);
		}

		@Override
		public void sendMessage(ChatAidl info) throws RemoteException {
			// TODO Auto-generated method stub
//			mClientChatManager.sendMessage(info);
		}

		@Override
		public void queryMsgList(int startRecord, int pageSize) throws RemoteException {
//			mClientChatManager.queryMsgList(startRecord, pageSize);
		}

		@Override
		public void queryHistoryMsgList() throws RemoteException {
//			mClientChatManager.queryUserList(0);
		}

		@Override
		public void initImUser(String owner, ChatSnapCallback callback, int pageSize) throws RemoteException {
			// TODO Auto-generated method stub
//			mClientChatManager.initImUser(owner, callback, pageSize);
		}

		@Override
		public void unImUser() throws RemoteException {
			// TODO Auto-generated method stub
//			mClientChatManager.unImUser();
		}

		@Override
		public void updateUserInfo(String userId, String userName, String userHead, int whiteStatus) throws RemoteException {
			// TODO Auto-generated method stub
//			mClientChatManager.updateUserInfo(userId, userName, userHead, whiteStatus);
		}

		@Override
		public void unSendMessage() throws RemoteException {
			// TODO Auto-generated method stub
//			mClientChatManager.unSendMessage();
		}

		@Override
		public void updateUserUnread(int userId, int unread) throws RemoteException {
			// TODO Auto-generated method stub

		}

		@Override
		public void queryMapFriend(String userId, FriendCallback mFriendCallback) throws RemoteException {
			// TODO Auto-generated method stub
			mFriendManager.queryMapFriend(userId, mFriendCallback);
		}

		@Override
		public void queryListFriend(String userId, FriendCallback mFriendCallback) throws RemoteException {
			// TODO Auto-generated method stub
			mFriendManager.queryListFriend(userId, mFriendCallback);
		}

		@Override
		public void queryFriend(String owner, String userId, FriendCallback mFriendCallback) throws RemoteException {
			// TODO Auto-generated method stub
			mFriendManager.queryFriend(owner, userId, mFriendCallback);
		}

		@Override
		public void saveOrUpdateFriend(FriendAidl info, String userId) throws RemoteException {
			// TODO Auto-generated method stub
			mFriendManager.saveOrUpdateFriend(info, userId);
		}

		@Override
		public void initSms(SMSCallback mSMSCallback) throws RemoteException {
			// TODO Auto-generated method stub
//			mClientChatManager.initSms(mSMSCallback);
			mSmsManager.initSms(mSMSCallback);
		}

		@Override
		public SmsListAidl querySmsList(String smsType, String jid) throws RemoteException {
			// TODO Auto-generated method stub
			return mSmsManager.querySmsList(smsType, jid);
		}

		@Override
		public void deleteSmsInfo(String smsType, int id) throws RemoteException {
			// TODO Auto-generated method stub
			mSmsManager.deleteSmsInfo(smsType, id);
		}

		@Override
		public void updateSmsRead(String smsType, String userId) throws RemoteException {
			// TODO Auto-generated method stub
			mSmsManager.updateSmsRead(smsType, userId);
		}

		@Override
		public void unReadSmsQury(String jid) throws RemoteException {
			// TODO Auto-generated method stub
			mSmsManager.unReadSmsQury(jid);
		}

		@Override
		public boolean isNotifyAlert() throws RemoteException {
			// TODO Auto-generated method stub
			return ImPreferences.getInstance(ClientService.this).getPfBoolean(AppUtils.isNotifyAlert);
		}

		@Override
		public boolean isNotifyvibation() throws RemoteException {
			// TODO Auto-generated method stub
			return ImPreferences.getInstance(ClientService.this).getPfBoolean(AppUtils.isNotifyvibation);
		}

		@Override
		public boolean isNotifyOpen() throws RemoteException {
			// TODO Auto-generated method stub
			return ImPreferences.getInstance(ClientService.this).getPfBoolean(AppUtils.isNotifyOpen);
		}

		@Override
		public boolean setNotifyAlert(boolean flag) throws RemoteException {
			// TODO Auto-generated method stub
			ImPreferences.getInstance(ClientService.this).setPfBoolean(AppUtils.isNotifyAlert, flag);
			return true;
		}

		@Override
		public boolean setNotifyvibation(boolean flag) throws RemoteException {
			// TODO Auto-generated method stub
			ImPreferences.getInstance(ClientService.this).setPfBoolean(AppUtils.isNotifyvibation, flag);
			return true;
		}

		@Override
		public boolean setNotifyOpen(boolean flag) throws RemoteException {
			// TODO Auto-generated method stub
			ImPreferences.getInstance(ClientService.this).setPfBoolean(AppUtils.isNotifyOpen, flag);
			return true;
		}

		@Override
		public boolean addFriend(String mBarejid, String mName, String mMobile) throws RemoteException {
			// TODO Auto-generated method stub
//			try {
//				return mXMPPConnectionMg.getClientRosterManager().addFriend(mBarejid, mName, mMobile);
//			} catch (Exception e) {
				return false;
//			}
		}

		@Override
		public boolean deleteFriend(String mBarejid) throws RemoteException {
			// TODO Auto-generated method stub
//			try {
//				boolean flag=mXMPPConnectionMg.getClientRosterManager().deleteFriend(mBarejid);
//				mClientChatManager.deleteImUser(mBarejid);
//				return flag;
//			} catch (Exception e) {
				return false;
//			}
		}

		@Override
		public void updateUnReadPushCount(String owner, PushAidl pushMsg )
				throws RemoteException {
//			mPushManager.updateUnreadPushCount(owner, pushMsg);
			
		}

		@Override
		public void getAllServerFriends() throws RemoteException {
//			mXMPPConnectionMg.getClientRosterManager().setNetContactsOnlineStatus();
			
		}

		@Override
		public void initChat(ChatCallback mChatCallback) throws RemoteException {
			Log.v("imcommon", "clientservice initChatInfo "+mChatCallback);
//			if(mChatCallback!=null)
//			mClientChatManager.initChatBack(mChatCallback);
			
		}

		@Override
		public String createMucRoom(String nickname, String userId)
				throws RemoteException {
//			Log.i("clientservice","****createMucRoom***"+nickname+" userid:"+userId+" "+xMucChatManager);
//			return xMucChatManager.createMucRoom(userId, nickname, null, null);
			return null;
			
		}

		@Override
		public void sendMucMsg(MucChatAidl info) throws RemoteException {
			Log.i("clientservice","****sendMucMsg***"+info.info.mContent+" "+info.info.mPlatForm);
			ChatMessage cm=new ChatMessage();
			cm.setContent(info.info.mContent);
			cm.setFromUserId(info.info.fromUserId);
			cm.setFromUserName(info.info.mUserName);
			cm.setTimeSend(com.xspace.android.imcommon.utils.sk.TimeUtils.sk_time_current_time());
			cm.setRoomId(info.info.roomID);
			cm.setRoomName(info.info.roomName);
			cm.setFromUserLogo(info.info.fromUserLogo);
			cm.setType(info.info.mContentType);
			cm.setUuid(info.info.mUUID);
			cm.setPlatForm(info.info.mPlatForm);
//			xMucChatManager.sendMessage(info.info.mExHM.get("group_jid"), cm);
			
		}

		@Override
		public void inviteFriendToRoom(String roomId, String userId,
				String reason) throws RemoteException {
//			xMucChatManager.invite(roomId, userId, reason);
			
		}

		@Override
		public void joinToRoom(String roomId, String userId, String nickname)
				throws RemoteException {
//			xMucChatManager.joinMucChat(roomId, nickname, 0);
			
		}

		@Override
		public void kickFriendFromRoom(String roomId, String userId,
				String reason) throws RemoteException {
//			xMucChatManager.kickParticipant(roomId, userId);
			
		}

		@Override
		public void exitMucRoom(String roomId) throws RemoteException {
//		        xMucChatManager.exitMucChat(roomId);
			
		}
//file upload
		@Override
		public int getUploadStatus(long id) throws RemoteException {
			// TODO Auto-generated method stub
			return mUploadManager.getStatus(id);
		}

		@Override
		public float getUploadProgress(long id) throws RemoteException {
			// TODO Auto-generated method stub
			return mUploadManager.getProgress(id);
		}

		@Override
		public long getUploaded(long id) throws RemoteException {
			// TODO Auto-generated method stub
			return mUploadManager.getDowned(id);
		}

		@Override
		public void pauseUpload(long id) throws RemoteException {
			// TODO Auto-generated method stub
			mUploadManager.pause(id);
		}

		@Override
		public void resumeUpload(long id) throws RemoteException {
			// TODO Auto-generated method stub
			mUploadManager.resume(id);
		}

		@Override
		public void cancelUpload(long id) throws RemoteException {
			// TODO Auto-generated method stub
			mUploadManager.cancel(id);
		}

		@Override
		public void fileUpload(ChatListAidl uploadList, IUploadCallback callback)
				throws RemoteException {
			// TODO Auto-generated method stub
			mUploadManager.addTask(uploadList, callback);
		}

		@Override
		public ChatListAidl queryUploadList(String fromUserId, String toUserId)
				throws RemoteException {
			// TODO Auto-generated method stub
			return mUploadManager.findMsgList(fromUserId, toUserId);
		}

		@Override
		public void deleteFileMsg(long msgId) throws RemoteException {
			// TODO Auto-generated method stub
			mUploadManager.deleteMsg(msgId);
		}

		@Override
		public void resetCallback(long id, IUploadCallback callback)
				throws RemoteException {
			mUploadManager.setCallback(id,callback);
			
		}
	};
	private void setAlarmCheckService(Context context,long interval ) {
		Log.i("clientservice","*************setAlarmCheckService start*************");
		AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent();
		intent.setAction("com.im.XmppConnectCheckBroad");
		//sendBroadcast(intent);
		 pendingIntent = PendingIntent.getBroadcast(context, 0, intent,
				 PendingIntent.FLAG_UPDATE_CURRENT);
		alarm.setRepeating(AlarmManager.RTC, System.currentTimeMillis()+60*1000,
				interval, pendingIntent); 
	}
	
	private void cancelAlarm(Context context) {
		AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
		if(pendingIntent!=null)
		alarm.cancel(pendingIntent);
	}
	private void killService() {
		ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningAppProcessInfo> appProcessInfos = activityManager.getRunningAppProcesses();
		String currentProcess = getApplicationInfo().processName;
		for (RunningAppProcessInfo appProcessInfo : appProcessInfos) {
			String processName = appProcessInfo.processName;
			if (processName.equals(currentProcess)) {
				System.out.println("ApplicationInfo-->" + processName);
				activityManager.killBackgroundProcesses(processName);
			}
		}
	}
}
